import {defineStore} from 'pinia'
import type{ICartGoods} from '@/types/index'

export const useCartStore = defineStore('cart',{
    state(){
        return{
            list:[] as Array<ICartGoods>,
            stateAll:false,
        }
    },
    actions:{
        /**
         * 全选
         */
        checkAll(){
            // 设置全选状态
            this.stateAll = !this.stateAll
            // 根据全选状态设置所有单选状态
            this.list.forEach(item =>(item.state = this.stateAll));
        },
        /**
         * 单选
         */
        singleCheck(id:number){
            const goods:ICartGoods | undefined = this.list.find(item=>item.id === id)
            if(goods){
                goods.state = !goods.state
            }
            // 设置全选状态
            this.stateAll = this.list.every(item=>item.state)
        },
        /**
         * 保存
         */
        saveCart(goods:ICartGoods){
            //相同商品数量加一
            // 判断购物车是否由此商品，如果有数量加，没有作为新商品添加
            const oldGoods = this.list.find(item=>item.id === goods.id)
            if(oldGoods){
                oldGoods.num++
            }else{
                this.stateAll = false
                this.list.push(goods)
            }
        },
        /**
         * 删除
         */
        deleteGoods(id:number){
            const index = this.list.findIndex(item=>item.id === id)
            this.list.splice(index,1)
        }
    },
    getters:{
        totalPrice(){
            const sum = this.list.reduce((pre,cur)=>pre+(cur.state?cur.num*cur.price:0),0)
            return Number(sum.toFixed(2)*100)
        }
    },
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'cart',
                storage: sessionStorage,
                paths: ['list', 'stateAll'],
            },
        ],
    },
})